<?php

namespace Spider\Weibo\Utils;

use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;

class HttpClient
{
    private $client;
    private $cookieJar;
    private $redis;

    public function __construct()
    {
        $this->redis = RedisClient::getInstance();
        $this->initClient();
    }

    private function initClient(): void
    {
        $sub = $this->getOrCreateSub();
        $this->cookieJar = CookieJar::fromArray(['SUB' => $sub], 'weibo.com');
        $this->client = new Client([
            'timeout' => 10,
            'cookies' => $this->cookieJar,
            'headers' => [
                'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36',
                'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
                'Accept-Language' => 'zh-CN,zh;q=0.9,en;q=0.8'
            ]
        ]);
    }

    private function getOrCreateSub(): string
    {
        $sub = $this->redis->getSubInfo();
        if (!$sub) {
            $sub = self::createSub();
            $this->redis->setSubInfo($sub);
        }
        return $sub;
    }

    private function refreshSub(): void
    {
        $this->redis->deleteSubInfo();
        $this->initClient();
    }

    public function get(string $url, array $params = []): array
    {
        try {
            $response = $this->client->get($url, [
                'query' => $params
            ]);
            $result = json_decode($response->getBody()->getContents(), true);

            if (isset($result['error_code']) && $result['error_code'] == 401) {
                $this->refreshSub();
                return $this->get($url, $params); // 重试一次
            }

            if (isset($result['ok']) && $result['ok'] == -100) {
                $this->refreshSub();
                return $this->get($url, $params); // 重试一次
            }

            return $result;
        } catch (\Exception $e) {
            return [];
        }
    }

    public static function createSub(): string
    {
        $headers = [
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
            // 其他必要的请求头（根据实际需求补充）
        ];
        $data = [
            'cb' => 'visitor_gray_callback',
            'tid' => '',
            'from' => 'weibo',
        ];
        // 初始化 cURL 会话
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://passport.weibo.com/visitor/genvisitor2');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 返回结果不直接输出
        curl_setopt($ch, CURLOPT_POST, true); // 启用 POST 请求
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); // 编码 POST 数据
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); // 设置请求头
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 禁用 SSL 验证（可选）
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 禁用 SSL 验证（可选）
        // 发送请求并获取响应
        $response = curl_exec($ch);
        curl_close($ch);
        // 正则提取 JSON 数据
        preg_match('/{.*}/', $response, $matches);
        $json_data = json_decode($matches[0], true); // 解析为关联数组
        // 提取 sub 字段
        $sub = $json_data['data']['sub'];
        return $sub;
    }
}
